<?php

namespace app\adminapi\controller;

use app\model\CommentModel;
use app\model\UserModel;
use app\model\PostModel;
use Webman\Http\Request;

class Comment extends BaseAdminApi
{
    protected ?string $dataModel = CommentModel::class;
    protected array $with = ['user', 'post'];
    protected array $allowSearch = ['content', 'status', 'user_id', 'post_id', 'pid'];

    /**
     * 获取评论详情
     */
    public function getCommentDetail(Request $request)
    {
        $id = $request->get('id');
        
        if (empty($id)) {
            return $this->fail('评论ID不能为空');
        }

        try {
            $comment = CommentModel::with(['user', 'post', 'replyUser'])->find($id);
            
            if (!$comment) {
                return $this->fail('评论不存在');
            }

            return $this->success('获取评论详情成功', $comment);
        } catch (\Exception $e) {
            return $this->fail('获取评论详情失败：' . $e->getMessage());
        }
    }

    /**
     * 创建评论
     */
    public function createComment(Request $request)
    {
        $data = $request->post();
        
        // 验证必填字段
        if (empty($data['content'])) {
            return $this->fail('评论内容不能为空');
        }

        if (empty($data['user_id'])) {
            return $this->fail('用户ID不能为空');
        }

        if (empty($data['post_id'])) {
            return $this->fail('帖子ID不能为空');
        }

        // 验证字段长度
        if (mb_strlen($data['content']) > 500) {
            return $this->fail('评论内容不能超过500个字符');
        }

        // 验证用户是否存在
        $user = UserModel::find($data['user_id']);
        if (!$user) {
            return $this->fail('用户不存在');
        }

        // 验证帖子是否存在
        $post = PostModel::find($data['post_id']);
        if (!$post) {
            return $this->fail('帖子不存在');
        }

        try {
            $comment = new CommentModel();
            $comment->content = $data['content'];
            $comment->user_id = $data['user_id'];
            $comment->post_id = $data['post_id'];
            $comment->pid = $data['pid'] ?? 0;
            $comment->type = $data['type'] ?? 1;
            $comment->reply_user_id = $data['reply_user_id'] ?? null;
            $comment->status = $data['status'] ?? 1;
            $comment->thumb_num = 0;
            $comment->created_at = date('Y-m-d H:i:s');
            $comment->updated_at = date('Y-m-d H:i:s');
            
            $comment->save();
            
            // 增加对应帖子的comment_num字段
            PostModel::where('id', $data['post_id'])->increment('comment_num', 1);

            return $this->success('创建评论成功', $comment);
        } catch (\Exception $e) {
            return $this->fail('创建评论失败：' . $e->getMessage());
        }
    }

    /**
     * 更新评论
     */
    public function updateComment(Request $request)
    {
        $data = $request->post();
        
        if (empty($data['id'])) {
            return $this->fail('评论ID不能为空');
        }

        if (empty($data['content'])) {
            return $this->fail('评论内容不能为空');
        }

        // 验证字段长度
        if (mb_strlen($data['content']) > 500) {
            return $this->fail('评论内容不能超过500个字符');
        }

        try {
            $comment = CommentModel::find($data['id']);
            
            if (!$comment) {
                return $this->fail('评论不存在');
            }

            $comment->content = $data['content'];
            if (isset($data['status'])) {
                $comment->status = $data['status'];
            }
            $comment->updated_at = date('Y-m-d H:i:s');
            
            $comment->save();

            return $this->success('更新评论成功', $comment);
        } catch (\Exception $e) {
            return $this->fail('更新评论失败：' . $e->getMessage());
        }
    }

    /**
     * 删除评论
     */
    public function deleteComment(Request $request)
    {
        $data = $request->post();
        
        if (empty($data['id'])) {
            return $this->fail('评论ID不能为空');
        }

        try {
            $comment = CommentModel::find($data['id']);
            
            if (!$comment) {
                return $this->fail('评论不存在');
            }
            
            // 获取帖子ID用于更新评论数量
            $postId = $comment->post_id;
            
            $comment->delete();
            
            // 更新对应帖子的comment_num字段
            PostModel::where('id', $postId)->decrement('comment_num', 1);

            return $this->success('删除评论成功');
        } catch (\Exception $e) {
            return $this->fail('删除评论失败：' . $e->getMessage());
        }
    }

    /**
     * 批量删除评论
     */
    public function batchDeleteComments(Request $request)
    {
        $data = $request->post();
        
        if (empty($data['ids']) || !is_array($data['ids'])) {
            return $this->fail('请选择要删除的评论');
        }

        try {
            // 在删除前获取要删除的评论信息，特别是post_id
            $commentsToDelete = CommentModel::whereIn('id', $data['ids'])
                ->select('id', 'post_id')
                ->get();
            
            if ($commentsToDelete->isEmpty()) {
                return $this->fail('未找到要删除的评论');
            }
            
            // 统计每个帖子需要减少的评论数量
            $postCommentCounts = [];
            foreach ($commentsToDelete as $comment) {
                $postId = $comment->post_id;
                if (!isset($postCommentCounts[$postId])) {
                    $postCommentCounts[$postId] = 0;
                }
                $postCommentCounts[$postId]++;
            }

            // 执行删除操作
            $deleteCount = CommentModel::whereIn('id', $data['ids'])->delete();
            
            // 更新对应帖子的comment_num字段
            foreach ($postCommentCounts as $postId => $count) {
                PostModel::where('id', $postId)
                    ->decrement('comment_num', $count);
            }

            return $this->success(['deleted_count' => $deleteCount]);
        } catch (\Exception $e) {
            return $this->fail('批量删除失败：' . $e->getMessage());
        }
    }

    /**
     * 更新评论状态
     */
    public function updateCommentStatus(Request $request)
    {
        $data = $request->post();
        
        if (empty($data['id'])) {
            return $this->fail('评论ID不能为空');
        }

        if (!isset($data['status'])) {
            return $this->fail('状态不能为空');
        }

        try {
            $comment = CommentModel::find($data['id']);
            
            if (!$comment) {
                return $this->fail('评论不存在');
            }

            $comment->status = $data['status'];
            $comment->updated_at = date('Y-m-d H:i:s');
            
            $comment->save();

            $statusText = $data['status'] == 1 ? '启用' : '禁用';
            return $this->success($statusText . '评论成功', $comment);
        } catch (\Exception $e) {
            return $this->fail('更新评论状态失败：' . $e->getMessage());
        }
    }
}